<template>
    <div id="container"></div>
    <el-radio-group class="el-radio-group-style" v-model="isCollapse">
        <el-radio-button class="el-radio-button-style" :value="false">展开详情</el-radio-button>
        <el-radio-button class="el-radio-button-style" :value="true">隐藏详情</el-radio-button>
    </el-radio-group>

    <div class="sidebar-container">
        <el-menu class="el-menu-vertical-style" :collapse="isCollapse" @open="handleOpen" @close="handleClose">
            <el-sub-menu index="1">
                <template #title>
                    <img src="@/assets/images/时空分布.svg" style="width: 30px" />
                    <span class="title-style">城市意象时空分布</span>
                </template>
                <el-sub-menu index="1-space">
                    <template class="el-sub-menu-style" #title>
                        <span>空间分布</span>
                    </template>
                    <el-menu-item index="1-space-num"
                        @click="onSpaceContent(dataSets[0], numbers[0])">发文数</el-menu-item>
                    <el-menu-item index="1-space-like"
                        @click="onSpaceContent(dataSets[0], numbers[1])">点赞数</el-menu-item>
                    <el-menu-item index="1-space-collect"
                        @click="onSpaceContent(dataSets[0], numbers[2])">收藏数</el-menu-item>
                    <el-menu-item index="1-space-comment"
                        @click="onSpaceContent(dataSets[0], numbers[3])">评论数</el-menu-item>
                </el-sub-menu>
                <el-sub-menu index="1-time">
                    <template #title>
                        <span>时间分布</span>
                    </template>
                    <el-menu-item index="1-time-1"
                        @click="onTimeContent(timeSets[0], quarters[0])">2023年第一季度</el-menu-item>
                    <el-menu-item index="1-time-2"
                        @click="onTimeContent(timeSets[0], quarters[1])">2023年第二季度</el-menu-item>
                    <el-menu-item index="1-time-3"
                        @click="onTimeContent(timeSets[0], quarters[2])">2023年第三季度</el-menu-item>
                    <el-menu-item index="1-time-4"
                        @click="onTimeContent(timeSets[0], quarters[3])">2023年第四季度</el-menu-item>
                </el-sub-menu>
            </el-sub-menu>
            <el-sub-menu index="2">
                <template #title>
                    <img src="@/assets/images/感知特征分布.svg" style="width: 30px" />
                    <span class="title-style">城市意象感知特征分布</span>
                </template>
                <el-sub-menu index="2-poi">
                    <template #title>
                        <span>功能感知</span>
                    </template>
                    <el-menu-item index="2-poi-num" @click="onScoreContent(scoreSets[0], scores[0])">功能密度</el-menu-item>
                    <el-menu-item index="2-poi-mix"
                        @click="onScoreContent(scoreSets[0], scores[1])">功能混合度</el-menu-item>
                </el-sub-menu>
                <el-sub-menu index="2-sdna">
                    <template #title>
                        <span>句法感知</span>
                    </template>
                    <el-menu-item index="2-sdna-nqpda"
                        @click="onScoreContent(scoreSets[0], scores[2])">整合度</el-menu-item>
                    <el-menu-item index="2-sdna-betweenness"
                        @click="onScoreContent(scoreSets[0], scores[3])">穿行度</el-menu-item>
                </el-sub-menu>
                <el-sub-menu index="2-eye">
                    <template #title>
                        <span>视觉感知</span>
                    </template>
                    <el-menu-item index="2-eye-sky"
                        @click="onScoreContent(scoreSets[0], scores[4])">天空开阔度</el-menu-item>
                    <el-menu-item index="2-eye-green"
                        @click="onScoreContent(scoreSets[0], scores[5])">绿视度</el-menu-item>
                </el-sub-menu>
                <el-sub-menu index="2-emotion">
                    <template #title>
                        <span>情绪感知</span>
                    </template>
                    <el-menu-item index="2-emotion-positive"
                        @click="onScoreContent(scoreSets[0], scores[6])">积极情绪</el-menu-item>
                </el-sub-menu>
            </el-sub-menu>
        </el-menu>
    </div>


    <div id="ranking-container">
        <div id="title-list"></div>
        <ul id="ranking-list"></ul>
    </div>
</template>

<script setup>

import AMapLoader from '@amap/amap-jsapi-loader';
import { shallowRef, ref, onMounted } from 'vue';
import geoJsonDataUrl from '@/geoJson/index.js';
import dataSets from '@/geoJson/index1.js';
import timeSets from '@/geoJson/index2.js';
import scoreSets from '@/geoJson/index3.js';
import { getParkList } from "@/api/api.js"

const path = ref([]);
const current_position = ref([]);
let map = null;
let AMap = null;
let infoWindow = null;
let numbers = ["发文数", "点赞数", "收藏数", "评论数"];
let quarters = ["第一季度", "第二季度", "第三季度", "第四季度"];
let scores = ["功能密度", "功能混合度", "整合度", "穿行度", "天空开阔度", "绿视度", "积极情绪"]
let fillColors = ["rgba(0,62,179,1)", "rgba(255,77,79,1)", "rgba(250,140,22,1)", "rgba(82,196,26,1)",
    "rgba(204,0,0,1)", "rgba(255,128,0,1)", "rgba(68,158,251,1)", "rgba(255,255,0,1)"];
const isCollapse = ref(true);
let currentIndex = 0;
let scrollInterval;

onMounted(async () => {
    initMap();
});

function initMap() {

    window._AMapSecurityConfig = {
        securityJsCode: '6fefce89f100008adcf57cabde46954c',
    };

    AMapLoader.load({
        key: 'b237beffe0d9b099b7e6743a2f4a9fb9',
        version: '2.0',
    })
        .then((AMapInstance) => {
            AMap = AMapInstance; // 将 AMapInstance 分配给全局变量 AMap
            map = new AMap.Map('container', {
                viewMode: '3D',
                zoom: 18,
                // center: [118.126064, 24.501628],
            });

            AMap.plugin(
                ["AMap.ToolBar", "AMap.Scale", "AMap.HawkEye", "AMap.Geolocation", "AMap.MapType", "AMap.MouseTool", "AMap.GeoJSON", "AMap.HeatMap"],

                function () {
                    //异步同时加载多个插件
                    // 添加地图插件
                    const toolBar = new AMap.ToolBar({
                        position: { bottom: '200px', right: '20px' },
                        direction: 'horizontal',
                    })
                    map.addControl(toolBar); // 工具条控件;范围选择控件

                    map.addControl(new AMap.Scale()); // 显示当前地图中心的比例尺
                    map.addControl(new AMap.HawkEye()); // 显示缩略图
                    map.addControl(new AMap.MapType()); // 实现默认图层与卫星图,实时交通图层之间切换

                    // 创建定位实例
                    const geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true, // 是否使用高精度定位
                        timeout: 10000,           // 超时时间
                        showMarker: true,         // 是否显示定位点
                        panToLocation: true,      // 定位成功后是否自动平移到定位点
                        showCircle: false,
                        position: { bottom: '280px', right: '20px' },
                    });

                    // 添加定位控件
                    map.addControl(geolocation);

                    // 自动获取当前位置
                    geolocation.getCurrentPosition((status, result) => {
                        if (status === 'complete') {
                            // 定位成功
                            const position = result.position; // 用户的经纬度信息
                            map.setCenter(position); // 将地图中心设置为用户的位置
                        } else {
                            // 定位失败
                            console.error('定位失败：', result.message);
                        }
                    });

                    console.log("热力图插件加载成功")
                    const heatmap = new AMap.HeatMap(map, {
                        radius: 50, // 热力图点的半径
                        opacity: [0.6, 0.9], // 热力图透明度
                    });

                    // 初始加载人流数据
                    updateHeatmapData(heatmap);

                    // 设置每30秒自动更新一次人流数据
                    setInterval(() => {
                        updateHeatmapData(heatmap);
                    }, 30000); // 每 30 秒更新一次

                }
            );
                
            // 单击
            map.on('click', (e) => {
                // lng ==> 经度值  lat => 维度值
                current_position.value = [e.lnglat.lng, e.lnglat.lat];
                path.value.push([e.lnglat.lng, e.lnglat.lat]);
            })

            //加载城市意象点数据
            // LoadGeoJson(map, geoJsonDataUrl);

            //加载厦门市停车场数据
            loadParkingDataOnMap(map)

            // 初始化信息窗口
            infoWindow = new AMap.InfoWindow({
                isCustom: true,  //使用自定义窗体
                offset: new AMap.Pixel(0, -30)
            });


        }).catch((e) => {
            console.error('AMapLoader加载错误:', e);
        });
}

// 更新人流热力图数据
function updateHeatmapData(heatmap) {
    // 模拟获取后台数据的过程，从后端获取停车场信息，模拟更新最新人流量数据
    const flowData = fetchFlowData();

    heatmap.setDataSet({
        data: flowData, // 热力图数据
        max: 100        // 热力图的最大值
    });
}

// 模拟的获取实时人流量数据的函数
function fetchFlowData() {
    // 示例数据
    return [
        { lng: 118.126064, lat: 24.501628, count: 100 },
        { lng: 118.126564, lat: 24.502128, count: 90 },
        { lng: 118.127064, lat: 24.503128, count: 60 },
    ];
}

// 加载并显示停车场数据的函数
async function loadParkingDataOnMap(map) {
    try {
        //获取数据库中厦门停车场数据
        const { data: parkList } = await getParkList(1, 3370);
        console.log(parkList.page.list)

        // 加载停车场数据到地图上
        loadParkingData(map, parkList);
    } catch (error) {
        console.error('获取停车场数据失败：', error);
    }
}

// 显示停车场数据在地图上的函数
const loadParkingData = (map, parkingData) => {
    parkingData.page.list.forEach(item => {
        // 解析经纬度
        const [lng, lat] = item.coordinate.split(',').map(coord => parseFloat(coord.trim()));
        const position = new AMap.LngLat(lng, lat); // 创建经纬度对象

        // 创建标记
        const marker = new AMap.Marker({
            position: position,
            title: item.parkName, // 设置停车场名称作为标记的 title
            map: map // 将标记添加到地图
        });

        // 自定义图标
        const icon = new AMap.Icon({
            image: new URL('@/assets/空闲停车场.png', import.meta.url).href, // 自定义图标URL
            size: new AMap.Size(48, 48),
            imageSize: new AMap.Size(25, 25)
        });
        marker.setIcon(icon); // 设置自定义图标

        // 绑定停车场相关的扩展数据
        marker.setExtData({
            address: item.address,
            parkName: item.parkName,
            totalSlots: item.bussinessSlotNum,
            idleSlots: item.idleSlotCount,
            phone: item.parkPrincipalPhone
        });

        // 添加点击事件，显示停车场详细信息
        marker.on('click',parkingMarker)
    });

    // 调整视图以适应所有标记
    map.setFitView();
};

//点击停车场要素弹框事件
const parkingMarker = (e) => {
    const popupContent = createParkingInfoWindow(e);
    infoWindow.setContent(popupContent);
    infoWindow.setOffset(new AMap.Pixel(0, -50));
    infoWindow.open(map, e.target.getPosition());
}

//构建停车场自定义信息窗体
const createParkingInfoWindow = (e) => {
    const info = document.createElement('div');
    info.className = "customInfo";
    info.style.width = "300px";
    info.style.height = "auto";
    info.style.backgroundColor = "rgba(230,244,255,0.4)";
    info.style.border = "solid 3px white";
    info.style.borderRadius = "10px";

    //定义顶部标题
    const top = document.createElement("div");
    const titleContent = document.createElement("div");
    const close = document.createElement("button");
    top.className = "customTop";
    top.style.backgroundColor = "rgba(255,77,79,0.8)";
    top.style.height = "40px";
    top.style.borderTopLeftRadius = "10px";
    top.style.borderTopRightRadius = "10px";
    titleContent.innerHTML = e.target.getExtData().parkName;
    //titleContent.style.color = "white";
    titleContent.style.display = "inline-block";
    titleContent.style.padding = "8px";
    titleContent.style.fontWeight = "bold";
    titleContent.style.fontSize = "large";
    close.innerHTML = '✖';
    close.style.position = 'absolute';
    close.style.top = '8px';
    close.style.right = '8px';
    close.style.background = 'none';
    close.style.border = 'none';
    close.style.fontSize = '20px';
    close.style.color = "white";
    close.style.cursor = 'pointer';
    close.onclick = closeInfoWindow;

    top.appendChild(titleContent);
    top.appendChild(close);
    info.appendChild(top);

    //定义主题内容
    const middle = document.createElement("div");
    const content = [];
    content.push(e.target.getExtData().address);
    content.push(e.target.getExtData().totalSlots);
    content.push(e.target.getExtData().idleSlots);
    content.push(e.target.getExtData().phone);
    middle.className = "customMiddle";
    middle.innerHTML = "<strong>地址：</strong>" + content[0] + "<br>" +
                        "<strong>总车位：</strong>" + content[1] + "<br>" +
                        "<strong>空余车位：</strong>" + content[2] + "<br>" +
                        "<strong>联系电话：</strong>" + content[3];
    middle.style.padding = "10px 0 10px 8px";
    middle.style.lineHeight = "1.8";
    info.appendChild(middle);

    return info;
}

//关闭信息窗体
const closeInfoWindow = () => {
    map.clearInfoWindow();
}

</script>

<style scoped>
#container {
    padding: 0px;
    margin: 0px;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0%;
    left: 0%;
}

.el-radio-group-style {
    top: 10px;
    left: 5px;
}

.sidebar-container {
    width: 320px;
    min-height: auto;
    max-height: 400px;
    overflow-y: auto;
}

.el-menu-vertical-style:not(.el-menu--collapse)::-webkit-scrollbar {
    width: 10px;
    /* 滚动条宽度 */
}

.el-menu-vertical-style:not(.el-menu--collapse)::-webkit-scrollbar-track {
    background: #f1f1f1;
    /* 滚动条轨道颜色 */
    border-radius: 10px;
    /* 轨道圆角 */
}

.el-menu-vertical-style:not(.el-menu--collapse)::-webkit-scrollbar-thumb {
    background: #75bcff85;
    /* 滚动条颜色 */
    border-radius: 10px;
    /* 滚动条圆角 */
}

.el-menu-vertical-style:not(.el-menu--collapse)::-webkit-scrollbar-thumb:hover {
    background: #025afd;
    /* 滚动条悬停颜色 */
}

.el-menu-vertical-style:not(.el-menu--collapse) {
    width: 320px;
    min-height: 400px;
    max-height: 400px;
    /* 限制最大高度为100% */
    position: absolute;
    top: 3rem;
    left: 5px;
    background-color: rgba(233, 233, 233, 0.6);
    border-radius: 10px;
    border: 3px solid rgba(0, 68, 255, 0.808);
    overflow-y: auto;
}

.el-menu-vertical-style {
    width: 70px;
    min-height: auto;
    position: absolute;
    top: 3rem;
    left: 5px;
    border-radius: 10px 10px 10px 10px;
}

.title-style {
    font-size: large;
    font-weight: 800;
    color: black;
    padding: 10px;
}

.el-sub-menu-style {
    background-color: rgba(119, 206, 240, 0.582);
}

#ranking-container {
    position: absolute;
    bottom: 50px;
    left: 5px;
    width: 315px;
    height: 230px;
    background-color: rgba(233, 233, 233, 0.6);
    border-radius: 10px;
    border: 3px solid rgba(0, 68, 255, 0.808);
}

#ranking-list {
    list-style-type: none;
    padding: 0 10px 0 10px;
    max-height: 160px;
    overflow: hidden;
    /* 隐藏超出的部分 */
}

.ranking-item {
    position: absolute;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 10px;
    /* 每个条目的高度 */
    transition: transform 1s;
    /* 平滑过渡 */
}

#ranking-container::-webkit-scrollbar {
    width: 10px;
    /* 滚动条宽度 */
}

#ranking-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    /* 滚动条轨道颜色 */
    border-radius: 10px;
    /* 轨道圆角 */
}

#ranking-container::-webkit-scrollbar-thumb {
    background: #75bcff85;
    /* 滚动条颜色 */
    border-radius: 10px;
    /* 滚动条圆角 */
}

#ranking-container::-webkit-scrollbar-thumb:hover {
    background: #025afd;
    /* 滚动条悬停颜色 */
}
</style>